package com.gdkm.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.gdkm.daomain.User;
import com.gdkm.util.DataSourceUtils;
//进行增删改查
public class UserDao {
	QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());

	// 新增用户
	public int addUser(User user) throws SQLException {
		String sql = "insert into user(username,password,gender,email,telephone,introduce,activeCode,state,role) values(?,?,?,?,?,?,?,?,?)";
		return runner.update(sql, user.getUsername(), user.getPassword(), user.getGender(), user.getEmail(),
				user.getTelephone(), user.getIntroduce(), user.getActiveCode(), user.getState(), user.getRole());
	}

	// 按照账号和密码查询用户
	public User findUserByUsernameAndPassword(String username, String password) throws SQLException {
		String sql = "select * from user where username=? and password=? and state=1";
		return runner.query(sql, new BeanHandler<User>(User.class), username, password);

	}

	// 查询所有用户
	public List<User> findAllUser() throws SQLException {
		String sql = "select * from user";
		return runner.query(sql, new BeanListHandler<User>(User.class));

	}

	// 按照激活码查找用户
	public User findUserByActiveCode(String activeCode) throws SQLException {
		String sql = "select * from user where activeCode=?";
		return runner.query(sql, new BeanHandler<User>(User.class), activeCode);
	}

	// 激活用户
	public void activeUser(String activeCode) throws SQLException {
		String sql = "update user set state=? where activecode=?";
		runner.update(sql, 1, activeCode);
	}

	// 根据id查找用户
	public User findUserById(int id) throws SQLException {
		String sql="select * from user where id=?";
		return runner.query(sql, new BeanHandler<User>(User.class), id);
	}
	// 根据id删除用户
	public int deleteUser(int id) throws SQLException{
		String sql ="delete from user where id=?";
		return runner.update(sql,id);
	}
	//根据id修改用户密码
	public int updatePassword(User user) throws SQLException{
		String sql="update user set password=? where id=?";
		return runner.update(sql,new Object[]{user.getPassword(),user.getId()});
	}
}
